import React, { useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Tabs,
  Tab,
  Grid,
  Chip,
  Divider,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  useTheme,
  useMediaQuery,
} from '@mui/material';
import { useSearchParams } from 'react-router-dom';
import GameCard from '../components/GameCard';
import ArticleIcon from '@mui/icons-material/Article';
import ForumIcon from '@mui/icons-material/Forum';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

// 模拟搜索结果数据
const mockSearchResults = {
  games: [
    {
      id: 1,
      title: "赛博朋克 2077",
      imageUrl: "https://via.placeholder.com/300x200",
      tags: ["动作", "RPG", "开放世界"],
      rating: 4.5,
      price: "¥298",
    },
    {
      id: 2,
      title: "赛博潮流",
      imageUrl: "https://via.placeholder.com/300x200",
      tags: ["动作", "独立游戏"],
      rating: 4.0,
      price: "¥68",
    },
  ],
  articles: [
    {
      id: 1,
      title: "赛博朋克2077最新更新内容详解",
      date: "2024-01-15",
      author: "游戏评测员",
      excerpt: "最新更新带来了全新的战斗系统和故事内容...",
    },
    {
      id: 2,
      title: "赛博朋克类游戏推荐",
      date: "2024-01-10",
      author: "游戏推荐官",
      excerpt: "除了赛博朋克2077，这些游戏也值得一试...",
    },
  ],
  discussions: [
    {
      id: 1,
      title: "赛博朋克2077 Bug反馈与解决方案",
      author: "玩家小明",
      replies: 42,
      lastActive: "2小时前",
    },
    {
      id: 2,
      title: "赛博朋克2077 剧情讨论",
      author: "剧情控",
      replies: 156,
      lastActive: "5小时前",
    },
  ],
};

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`search-tabpanel-${index}`}
      aria-labelledby={`search-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ py: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

const SearchResults: React.FC = () => {
  const [searchParams] = useSearchParams();
  const query = searchParams.get('q') || '';
  const [activeTab, setActiveTab] = useState(0);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setActiveTab(newValue);
  };

  const RelatedSearches = () => (
    <Card variant="outlined" sx={{ mb: 3 }}>
      <CardContent>
        <Typography variant="h6" gutterBottom>
          相关搜索
        </Typography>
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
          <Chip label="赛博朋克游戏" clickable />
          <Chip label="赛博朋克2077攻略" clickable />
          <Chip label="赛博朋克动作游戏" clickable />
          <Chip label="赛博朋克设定" clickable />
        </Box>
      </CardContent>
    </Card>
  );

  return (
    <Container maxWidth="xl" sx={{ py: 4 }}>
      {/* 搜索结果头部 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="h5" gutterBottom>
          "{query}" 的搜索结果
        </Typography>
        <Typography color="text.secondary">
          找到 {mockSearchResults.games.length + mockSearchResults.articles.length + mockSearchResults.discussions.length} 个相关结果
        </Typography>
      </Box>

      <RelatedSearches />

      {/* 搜索结果分类标签 */}
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          variant={isMobile ? "scrollable" : "standard"}
          scrollButtons={isMobile ? "auto" : false}
        >
          <Tab label={`游戏 (${mockSearchResults.games.length})`} />
          <Tab label={`文章 (${mockSearchResults.articles.length})`} />
          <Tab label={`讨论 (${mockSearchResults.discussions.length})`} />
        </Tabs>
      </Box>

      {/* 游戏结果 */}
      <TabPanel value={activeTab} index={0}>
        <Grid container spacing={3}>
          {mockSearchResults.games.map((game) => (
            <Grid item key={game.id} xs={12} sm={6} md={4} lg={3}>
              <GameCard game={game} />
            </Grid>
          ))}
        </Grid>
      </TabPanel>

      {/* 文章结果 */}
      <TabPanel value={activeTab} index={1}>
        <List>
          {mockSearchResults.articles.map((article) => (
            <React.Fragment key={article.id}>
              <ListItem alignItems="flex-start">
                <ListItemAvatar>
                  <Avatar>
                    <ArticleIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={article.title}
                  secondary={
                    <>
                      <Typography
                        component="span"
                        variant="body2"
                        color="text.primary"
                      >
                        {article.author}
                      </Typography>
                      {` — ${article.excerpt}`}
                      <br />
                      <Typography variant="caption" color="text.secondary">
                        {article.date}
                      </Typography>
                    </>
                  }
                />
              </ListItem>
              <Divider variant="inset" component="li" />
            </React.Fragment>
          ))}
        </List>
      </TabPanel>

      {/* 讨论结果 */}
      <TabPanel value={activeTab} index={2}>
        <List>
          {mockSearchResults.discussions.map((discussion) => (
            <React.Fragment key={discussion.id}>
              <ListItem alignItems="flex-start">
                <ListItemAvatar>
                  <Avatar>
                    <ForumIcon />
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={discussion.title}
                  secondary={
                    <>
                      <Typography
                        component="span"
                        variant="body2"
                        color="text.primary"
                      >
                        {discussion.author}
                      </Typography>
                      <br />
                      <Typography variant="caption" color="text.secondary">
                        {discussion.replies} 条回复 · 最后活跃于 {discussion.lastActive}
                      </Typography>
                    </>
                  }
                />
              </ListItem>
              <Divider variant="inset" component="li" />
            </React.Fragment>
          ))}
        </List>
      </TabPanel>
    </Container>
  );
};

export default SearchResults;
